#include "NetworkManager.h"

void main(char *argv[], int argc) {
	NetworkManager nm;
	Connection *c;
	char data[NETWORK_BUFLEN];

	c = nm.add();
	c->set("isListen", "true");
	c->set("port", "2244");
	nm.start(c);

/*	c = nm.add();
	c->set("host", "google.com");
	c->set("port", "80");
	nm.start(c);
	c->write("GET /\n");
*/

	while(true) {
		// Wait for some network traffic to occur, or a timeout of 200 milliseconds
		nm.waitForReady();

		if(nm.isNew()) {
			// one or more new connections have been established
			while(c = nm.getNewConnection()) {
				printf("[%d] New connection added.\n", c->socket);
			}
		}
		else if(nm.isData()) {
			// one or more connections have data ready
			while(c = nm.getDataConnection()) {
				printf("[%d] Recv: %s\r\n", c->socket, c->getData());

				// send bytes back to the connection which sent them in
				sprintf(data, "(back) %s\r\n", c->getData());
				c->write(data);
				// send bytes to all clients with the specified data/value
				sprintf(data, "(toall) %s\r\n", c->getData());
				nm.write("port", c->get("port"), data);

				// we are finished with the data, pop it off the queue
				c->pop();
			}
		}
		else if(nm.isDel()) {
			// one or more connections have been dropped
			while(c = nm.getDelConnection()) {
				printf("[%d] Connection dropped.\n", c->socket);

				// stop tracking the connection
				nm.del(c);
			}
		}
		else {
			// nothing happened on the network
		}
	}
}